/*
 * VariableDeclAst.cpp
 *
 *  Created on: 5 Nov 2010
 *      Author: kn308
 */

#include <MAlice/Ast/VariableDeclAst.h>
#include <MAlice/Ast/IntegerLiteralAst.h>
#include <MAlice/Ast/AssignmentOperatorAst.h>
#include <MAlice/Ast/CharacterLiteralAst.h>
#include <MAlice/Ast/StringLiteralAst.h>
#include <MAlice/Ast/TypeAst.h>

namespace MAlice
{

VariableDeclAst::VariableDeclAst(const string& name, TypeAst* type,
		ExpressionAst* size) :
	mName(name), mType(type), mSize(size)
{
}

VariableDeclAst::~VariableDeclAst()
{
	delete mType;
	delete mSize;
}

llvm::Value* VariableDeclAst::generate()
{
#	ifndef NDEBUG
	cout << "VariableDeclAst::generate()" << endl;
#	endif

	Value* value;
	Codegen* g = Codegen::get();
	Builder* builder = g->getBuilder();
	BasicBlock* bb = builder->GetInsertBlock();
	{
		// jump to the end of the function entry block
		builder->SetInsertPoint(&bb->getParent()->getEntryBlock());
		value = builder->CreateAlloca(mType->type(), mSize->generate(), Twine(mName));

		//
		g->pushVar(mName, value);

		// default value
		AssignmentOperatorAst(new VariableAst(mName), g->getDefaultValue(mType->getName())).generate();
	}
	builder->SetInsertPoint(bb);

	return value;
}

}
